package com.hllxd.hism.star.basic.service.config.mysql;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;

public class MybatisConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MybatisConfiguration.class);

    public static SqlSessionFactory getSqlSessionFactory(ResourceLoader resourceLoader, MybatisProperties properties, DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        log.debug("Mybatis SqlSessionFactoryBean set datasource: datasource is {}", dataSource.getClass());
        factory.setDataSource(dataSource);
        if (StringUtils.hasText(properties.getConfigLocation())) {
            log.debug("Loading mybatis configuration file");
            factory.setConfigLocation(resourceLoader.getResource(properties.getConfigLocation()));
        } else {
            log.debug("Setting 'application.properties' into Mybatis SqlSessionFactoryBean");
            factory.setTypeAliasesPackage(properties.getTypeAliasesPackage());
            factory.setTypeHandlersPackage(properties.getTypeHandlersPackage());
            factory.setMapperLocations(properties.resolveMapperLocations());
        }
        return factory.getObject();
    }

}
